<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use app\admin\model\AdminUser;
use think\Request;
use think\Session;
class Login extends Controller
{

    public function index()
    {
        return view('login/index');
    }

    public function login(Request $request)
    {

        if(!$request->isPost()){
            $this->success('登陆失败',url('admin/index/index'));
        }
        $data = input('post.');
        $auth = $data['auth'];
        $pwd = $data['pwd'];
        if($auth === '' || $pwd === ''){
            $this->success('登陆失败',url('admin/index/index'));
            return;
        }

        $pwd = md5($data['pwd']);


        $obj = model('user')->where(function ($query) use ($auth,$pwd) {
            $query->where('username',$auth)->where('password',$pwd)->where('status','1');
        })->whereOr(function ($query) use ($auth,$pwd) {
            $query->where('tel',$auth)->where('password',$pwd)->where('status','1');
        })->whereOr(function ($query) use ($auth,$pwd) {
            $query->where('email',$auth)->where('password',$pwd)->where('status','1');
        })->find();
        if(empty($obj)){
            $this->success('登陆失败，密码或用户名不存在',url('admin/index/index'));
            return;
        }
       $rows = $obj->getData();
        if($rows['id']>0){
            Session::set('auth',$rows);
            $arr = ['status'=>'1','message'=>'登陆成功'];
            $this->nodeSession();
            $this->success('成功登陆',url('admin/index/index'));
            return;
        }else{
            $arr = ['status'=>'0','message'=>'登录失败'];
            $this->success('登陆失败',url('admin/index/index'));
            return;
        }
    }

    public  function nodeSession()
    {

        $id = Session::get('auth')['id'];
        //dump($id);die();
        $rid = Db::name('user_role')->field('rid')->where('uid',$id)->select();

        //	二维数组转成一维数组
        $result = array_reduce($rid, function ($result, $value) {
            return array_merge($result, array_values($value));
        }, array());



        //根据rid 查询nid
        $nid = Db::name('role_node')->field('nid')->where('rid','in',$result)->select();


        ///
        $res = array_reduce($nid, function ($result, $value) {
            return array_merge($result, array_values($value));
        }, array());


        // 去处重复nid
        $newnid = array_unique($res);

        $cm =  Db::name('node')->field('controller,method')->where('id','in',$newnid)->select();
        $cjoinm = [];
        foreach($cm as $v){
            $controller = ucfirst($v['controller']);
            $method = strtolower($v['method']);
            $cjoinm[] = $controller.$method;
        }
        Session::set('cjoinm',$cjoinm);

    }

    public function exitLogin()
    {
        Session::clear();
        $this->success('已退出',url('admin/login/index'));
        return;

    }

}